var faultStatistics = new Object();
var energyRatio = new Object();
var faultTrendThisYear = new Array();
var faultTrendLastYear = new Array();

var degreeLastYear;
var degreeThisYear;
var baseDegree;
var rewardDegree;
var iframeUrl;
var isProd = true; //是否为生产环境，生产环境将采用内网IFRAME URL
$(function() {

    // 系统时间
    myTime();
    setInterval(function() {
        myTime();
    }, 1000);
	//温湿度
	getMonitorData();
	setInterval(function() {
		getMonitorData();
	}, 30*60*1000);
    //故障监视数据
    getFaultMonitoringData();
     setInterval(function() {
         getFaultMonitoringData();
     }, 1000);
    //故障统计数据
    getFaultStatisticsData();
    setInterval(function() {
        getFaultStatisticsData();
    }, 1000*60);
    //故障趋势数据
    getFaultTrendData();
    setInterval(function() {
        getFaultTrendData();
    },  1000*60*60*24);
    //引入iframe
    creatIframe();

    //能耗占比
    getEnergyRatio();
    setInterval(function() {
    	getEnergyRatio();
    },  1000*60*60*24);
    
    //能耗监测
    energyMonitor();
    setInterval(function() {
    	energyMonitor();
    },  1000*60*60*24);
    
    //水耗监测
    waterMonitor();
    setInterval(function() {
    	waterMonitor();
    },  1000*60*60*24);
    
    //能耗趋势
    getEnergyTrendData();
    setInterval(function() {
    	getEnergyTrendData();
    },  1000*60*60*24);

});

//生成iframe url
function setIframeUrl(){
	if(isProd){
		//生产环境url
		var origin = window.location.origin;
		origin = origin.replace(window.location.port,"9020"); //SVG与此项目同IP不同端口
		iframeUrl = origin + "/bip/last-location.html";
	}else{
		//测试环境url
		iframeUrl = "http://dev.lziot.cn:8080/bip/last-location.html";
	}
}

function getMonitorData(){
	sendAjaxRequest('index/monitor', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.temperature").html(jsonObj.data.monitorData.temperature);
			$("div.precipitation").html(jsonObj.data.monitorData.precipitation);
			//$("div.pm2").html(jsonObj.data.monitorData.pm2);
			$("div.ppm p:eq(0)").html(jsonObj.data.monitorData.ppm);
		}else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

//引入iframe
function creatIframe(){
	setIframeUrl();
    $("div.iframe").append(
        "<iframe align=\"left\" width=\"1155px\" height=\"900px\" frameborder=\"no\" src="+iframeUrl+"></iframe>"
    )
}

//故障监视
function getFaultMonitoringData() {
    sendAjaxRequest('device/getFaultMonitoringData', null, null, function(data) {
        var jsonObj = eval("(" + data.data + ")");
        if (jsonObj.type == "success") {
            $("div.fas").html(jsonObj.data.faultMonitoringData.fas);
            $("div.emcs").html(jsonObj.data.faultMonitoringData.emcs);
            $("div.psdUp").html(jsonObj.data.faultMonitoringData.psdUp);
            $("div.psdDpwn").html(jsonObj.data.faultMonitoringData.psdDpwn);
            $("div.afc").html(jsonObj.data.faultMonitoringData.afc);
            $("div.acs").html(jsonObj.data.faultMonitoringData.acs);
            $("div.pis").html(jsonObj.data.faultMonitoringData.pis);
            $("div.pa").html(jsonObj.data.faultMonitoringData.pa);
            $("div.cctv").html(jsonObj.data.faultMonitoringData.cctv);
        } else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
        }
    })
}

function myTime() {
    var a = new Date();
    var time = a.toLocaleTimeString();
    var date = a.toLocaleDateString();
    $("span.date").html(date);
    $("span.time").html(time);
}

$("div.home").click(function(){
    document.location.href= "index.html" ;
});
$("div.person").click(function(){
    document.location.href= "personnel.html" ;
});
$(".gzzx").click(function(){
	document.location.href= "gzzx.html" ;
});

//故障统计数据
function getFaultStatisticsData(){
    sendAjaxRequest('device/getFaultStatisticsData', null, null, function(data) {
        var jsonObj = eval("(" + data.data + ")");
        if (jsonObj.type == "success") {
        	if(jsonObj.data.faultStatisticsData.xData.length == 0){
        		faultStatistics.xData =new Array("房建装饰 ", "自动扶梯", "区间照明 ", "FAS系统");
        		faultStatistics.yData =new Array(0,0,0,0);
        	}else{
        		faultStatistics.xData = jsonObj.data.faultStatisticsData.xData;
        		faultStatistics.yData = jsonObj.data.faultStatisticsData.yData;
        	}
            faultStatisticsDataHandler();
        } else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
        }
    })
}

//故障趋势
function getFaultTrendData() {

    sendAjaxRequest('device/getFaultTrendData', null, null, function(data) {
        var jsonObj = eval("(" + data.data + ")");
        if (jsonObj.type == "success") {
            faultTrendThisYear = jsonObj.data.faultTrendData.faultTrendThisYear;
            faultTrendLastYear = jsonObj.data.faultTrendData.faultTrendLastYear;
            faultTrendDataHandler();
        } else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
        }
    })
}

function faultStatisticsDataHandler() {
    var legendData = new Array();
    var seriesData = new Array();
    var totalNum = 0;
    var percent = 0;

    if(!(faultStatistics.xData == "" || faultStatistics.xData== null || faultStatistics.xData == undefined)){
        for (var i = 0; i < faultStatistics.xData.length; i++) {
            totalNum = totalNum + faultStatistics.yData[i];
        }
        for (var i = 0; i < faultStatistics.xData.length; i++) {
        	if(totalNum==0){
        		percent = 0;
        	}else{
        		percent = (faultStatistics.yData[i] / totalNum * 100).toFixed(2);
        	}
            var legendStr = faultStatistics.xData[i] +"("+percent+"%)";
            legendData[i] = legendStr;
            var obj = new Object();
            obj.value = faultStatistics.yData[i];
            obj.name = faultStatistics.xData[i]+"("+percent+"%)";
            seriesData[i] = obj;
        }
    }
    // 故障统计
    var faultStatisticsData = {
        legendLeft: 'left',
        legendTop: 20,
        legendLeft : 200,
        legendData: legendData,
        seriesCenter: ['30%', '50%'],
        seriesRadius: ['55%', '90%'],
        seriesData: seriesData,
    }
    var faultStatisticsDom = echarts.init(document.getElementById('faultStatistics'));
    faultStatisticsChart(faultStatisticsDom, faultStatisticsData);
    $("div.faultNum").html(totalNum);
}

function faultTrendDataHandler() {
        // 故障趋势
        var faultTrendData = {
            legendData: ['去年','今年'],
            xData: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            seriesLastYear:faultTrendLastYear,
            seriesThisYear: faultTrendThisYear
        }
        var faultTrendDom = echarts.init(document.getElementById('faultTrend'));
        brokenLineChart(faultTrendDom,faultTrendData)
}

//能耗占比
function getEnergyRatio() {
	sendAjaxRequest('device/getEnergyRatio', null, null, function(data){
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {

	         energyRatio.type = jsonObj.data.ddPercentObj.type;
	         energyRatio.degree = jsonObj.data.ddPercentObj.degree;
	         energyRatioData();

		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}
//水耗监测
function waterMonitor(){
	sendAjaxRequest('device/getWaterMonitorData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			
		
			$("div.water").html(jsonObj.data.waterAll);
			
			if(jsonObj.data.waterLastYear> 0 ){
				$("div.lastYear-water").attr("style","color: #991D40");
				$("div.energyMonitor").append("<img class='year-water' src='../images/arrow1.png'>");
			}else{
				$("div.lastYear-water").attr("style","color: #A6B91B");
				$("div.energyMonitor").append("<img class='year-water' src='../images/arrow2.png'>");
			}
			$("div.lastYear-water").html(jsonObj.data.waterLastYear+"%");
			
			if(jsonObj.data.waterLastMonth> 0 ){
				$("div.lastMonth-water").attr("style","color: #991D40");
				$("div.energyMonitor").append("<img class='month-water' src='../images/arrow1.png'>");
			}else{
				$("div.lastMonth-water").attr("style","color: #A6B91B");
				$("div.energyMonitor").append("<img class='month-water' src='../images/arrow2.png'>");
			}
			$("div.lastMonth-water").html(jsonObj.data.waterLastMonth+"%");
			
			console.log(jsonObj.data.waterLastDays);
			if(jsonObj.data.waterLastDays> 0 ){
				$("div.lastDays-water").attr("style","color: #991D40");
				$("div.energyMonitor").append("<img class='day-water' src='../images/arrow1.png'>");
			}else{
				$("div.lastDays-water").attr("style","color: #A6B91B");
				$("div.energyMonitor").append("<img class='day-water' src='../images/arrow2.png'>");
			}
			$("div.lastDays-water").html(Math.abs(jsonObj.data.waterLastDays)+"%");
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

//能耗监测
function energyMonitor(){
	sendAjaxRequest('device/getEnergyMonitorData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			$("div.electricity").html(jsonObj.data.eleAll);
			if(jsonObj.data.eleLastYear > 0 ){
				$("div.lastYear-electricity").attr("style","color: #991D40");
				$("div.energyMonitor").append("<img class='year-ele' src='../images/arrow1.png'>");
			}else{
				$("div.lastYear-electricity").attr("style","color: #A6B91B");
				$("div.energyMonitor").append("<img class='year-ele' src='../images/arrow2.png'>");
			}
			$("div.lastYear-electricity").html(jsonObj.data.eleLastYear+"%");
			
			if(jsonObj.data.eleLastMonth> 0 ){
				$("div.lastMonth-electricity").attr("style","color: #991D40");
				$("div.energyMonitor").append("<img class='month-ele' src='../images/arrow1.png'>");
			}else{
				$("div.lastMonth-electricity").attr("style","color: #A6B91B");
				$("div.energyMonitor").append("<img class='month-ele' src='../images/arrow2.png'>");
			}
			$("div.lastMonth-electricity").html(jsonObj.data.eleLastMonth+"%");
		
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	})
}

// 能耗趋势
function getEnergyTrendData() {
	sendAjaxRequest('device/getEnergyTrendData', null, null, function(data) {
		var jsonObj = eval("(" + data.data + ")");
		if (jsonObj.type == "success") {
			degreeLastYear = jsonObj.data.energyTrendData.degreeLastYear;
			degreeThisYear = jsonObj.data.energyTrendData.degreeThisYear;
			baseDegree = jsonObj.data.energyTrendData.baseDegree;
			rewardDegree = jsonObj.data.energyTrendData.rewardDegree;
		} else if (jsonObj.type == "fail") {
			console.log(jsonObj.message);
		}
	});
	var energyTrendData = {
		legendData : [ '去年', '今年', '考核指标线','奖励指标线' ],
		xData : [ '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月',
				'10月', '11月', '12月' ],
		seriesLastYear : degreeLastYear,
		seriesThisYear : degreeThisYear,
		baseDegree : baseDegree,
		rewardDegree : rewardDegree
	}
	var energyTrendDom = echarts.init(document.getElementById('energyTrend'));
	energyLineChart(energyTrendDom, energyTrendData)
}
function energyRatioData() {

	var legendData = new Array();
	var seriesData = new Array();

    var totalNum = 0;
    var percent = 0;
    for (var i = 0; i < energyRatio.degree.length; i++) {
        totalNum = totalNum + parseInt(energyRatio.degree[i]);
    }
    for (var i = 0; i < energyRatio.type.length; i++) {
        percent = (energyRatio.degree[i] / totalNum * 100).toFixed(2);
        var legendStr = energyRatio.type[i]+"("+percent+"%)";
        legendData[i] = legendStr;
        if(percent == 0){
        	percent=0.01;
        }
        var obj = new Object();
        obj.value = energyRatio.degree[i];
        obj.name = energyRatio.type[i]+"("+percent+"%)";
        seriesData[i] = obj;
    }

    var energyRatioData = {
    	legendLeft: 'auto',
	    legendTop: 15,
	    legendRight: 15,
        legendData: legendData,
        seriesCenter: ['30%', '50%'],
        seriesRadius: '75%',
        seriesData: seriesData,
    }
    var energyRatioDom = echarts.init(document.getElementById('energyRatio'));
    faultStatisticsChart(energyRatioDom,energyRatioData);

}


function faultStatisticsChart(chart,data) {
    // chart.clear();
    option = {
       tooltip: {
           trigger: 'item',
           formatter: "{b} : {c}"
    	},
        legend: {
            orient: 'vertical',
            left: data.legendLeft,
            top: data.legendTop,
            right: data.legendRight,
            itemWidth: 12,
            itemHeight: 12,
            data:data.legendData,
            textStyle: {
                fontSize: 12,
                color: '#fff'
            }
        },
        series: [
            {
                name:'访问来源',
                type:'pie',
                legendHoverLink: false,
                hoverAnimation: false,
                center: data.seriesCenter,
                radius: data.seriesRadius,
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: false,
                    },
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:data.seriesData
            }
        ]
    };

    chart.setOption(option);
}

function brokenLineChart(chart,data){
    // chart.clear();
    option = {
	    tooltip: {
	        trigger: 'axis'
	    },
        legend: {
            top: 25,
            data:data.legendData,
            textStyle: {
                fontSize: 12,
                color: '#fff'
            }
        },
        grid: {
            left: 53,
            x: 1000,
        },
        xAxis: {
            type: 'category',
            // boundaryGap: true,
            data: data.xData,
            axisTick: {
                show: false,
            },
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                // show: false
                fontSize: 12,
                color: '#fff',
                interval: 0,
                rotate:40
            }
        },
        yAxis: {
            type: 'value',
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dotted'
                }
            },
            splitNumber: 4,
            axisLabel: {
                fontSize: 12,
                color: '#fff'
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            axisTick: {
                show: true,
            },
        },
        series: [
            {
                type: 'line',
                name: '去年',
                symbol: 'circle',
                symbolSize: 3,
                data: data.seriesLastYear,
                itemStyle: {
                    normal: {
                        color: 'orange'
                    }
                }
            },
            {
                type: 'line',
                name: '今年',
                symbol: 'circle',
                symbolSize: 3,
                data: data.seriesThisYear,
                itemStyle: {
                    normal: {
                        color: 'yellow'
                    }
                }
            }
        ]
    };
    chart.setOption(option);
}

function energyLineChart(chart,data){
    // chart.clear();
    option = {
	    tooltip: {
	        trigger: 'axis'
	    },
        legend: {
            top: 25,
            data:data.legendData,
            textStyle: {
                fontSize: 12,
                color: '#fff'
            }
        },
        grid: {
            left: 70,
            x: 1000,
        },
        xAxis: {
            type: 'category',
            // boundaryGap: true,
            data: data.xData,
            axisTick: {
                show: false,
            },
            axisLine: {
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                // show: false
                fontSize: 12,
                color: '#fff',
                interval: 0,
                rotate:40
            }
        },
        yAxis: {
            type: 'value',
            splitLine: {
                show: true,
                lineStyle: {
                    type: 'dotted'
                }
            },
            splitNumber: 4,
            axisLabel: {
                fontSize: 12,
                color: '#fff'
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff',
                    width: 1
                }
            },
            axisTick: {
                show: true,
            },
        },
        series: [
            {
                type: 'line',
                name: '去年',
                symbol: 'circle',
                symbolSize: 3,
                data: data.seriesLastYear,
                itemStyle: {
                    normal: {
                        color: 'orange'
                    }
                }
            },
            {
                type: 'line',
                name: '今年',
                symbol: 'circle',
                symbolSize: 3,
                data: data.seriesThisYear,
                itemStyle: {
                    normal: {
                        color: 'yellow'
                    }
                }
            },
            {
                type: 'line',
                name: '考核指标线',
                symbol: 'circle',
                symbolSize: 3,
                data: data.baseDegree,
                itemStyle: {
                    normal: {
                        color: 'red'
                    }
                }
            },
            {
                type: 'line',
                name: '奖励指标线',
                symbol: 'circle',
                symbolSize: 3,
                data: data.rewardDegree,
                itemStyle: {
                    normal: {
                        color: '#7CFC00'
                    }
                }
            }
        ]
    };
    chart.setOption(option);
}
